package com.expert.miniapp.service.impl;

import com.expert.miniapp.dao.User;
import com.expert.miniapp.dao.UserMapper;
import com.expert.miniapp.dto.LoginResponse;
import com.expert.miniapp.dto.UpdateProfileRequest;
import com.expert.miniapp.dto.UserDTO;
import com.expert.miniapp.service.UserService;
import com.expert.miniapp.service.WechatService;
import com.expert.miniapp.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.UUID;

/**
 * UserServiceImpl - 用户服务实现类
 *
 * @author System
 * @since 2025-01-14
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    @Transactional
    public LoginResponse wechatLogin(String code) throws Exception {
        // 1. 调用微信API获取openid
        Map<String, String> wechatResult = wechatService.code2Session(code);
        String openid = wechatResult.get("openid");

        if (openid == null || openid.isEmpty()) {
            throw new Exception("获取微信OpenID失败");
        }

        logger.info("微信登录: openid={}", openid);

        // 2. 查询用户是否存在
        User user = userMapper.selectByWechatOpenid(openid);
        boolean isNewUser = (user == null);

        if (isNewUser) {
            // 3. 新用户，创建用户记录
            user = createNewUser(openid);
            logger.info("创建新用户: userId={}, username={}", user.getUserId(), user.getUsername());
        } else {
            // 4. 老用户，更新最后登录时间
            userMapper.updateLastLoginAt(user.getUserId());
            logger.info("用户登录: userId={}, username={}", user.getUserId(), user.getUsername());
        }

        // 5. 生成JWT Token
        String token = jwtUtil.generateToken(user.getUserId(), user.getWechatOpenid(), user.getUsername());

        // 6. 构造响应
        UserDTO userDTO = convertToDTO(user);
        LoginResponse response = new LoginResponse(token, isNewUser, userDTO);

        return response;
    }

    @Override
    public UserDTO getUserById(String userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return null;
        }
        return convertToDTO(user);
    }

    @Override
    @Transactional
    public UserDTO updateProfile(String userId, UpdateProfileRequest request) {
        // 查询用户
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        // 更新字段（只更新非null的字段）
        if (request.getNickname() != null) {
            user.setNickname(request.getNickname());
        }
        if (request.getAvatarUrl() != null) {
            user.setAvatarUrl(request.getAvatarUrl());
        }
        if (request.getPhone() != null) {
            user.setPhone(request.getPhone());
        }
        if (request.getEmail() != null) {
            user.setEmail(request.getEmail());
        }
        if (request.getOrgName() != null) {
            user.setOrgName(request.getOrgName());
        }
        if (request.getOrgSize() != null) {
            user.setOrgSize(request.getOrgSize());
        }
        if (request.getRegionCity() != null) {
            user.setRegionCity(request.getRegionCity());
        }
        if (request.getOrgRole() != null) {
            user.setOrgRole(request.getOrgRole());
        }

        // 保存更新
        int rows = userMapper.update(user);
        if (rows == 0) {
            throw new RuntimeException("更新用户信息失败");
        }

        logger.info("更新用户信息成功: userId={}", userId);

        // 返回最新的用户信息
        return getUserById(userId);
    }

    @Override
    @Transactional
    public String generateUsername() {
        // 获取当前日期
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy_MM_dd");
        String datePart = now.format(formatter);

        // 查询今天创建的用户数量
        int todayCount = userMapper.countTodayUsers();

        // 生成序号（从1开始，格式化为3位数）
        int sequence = todayCount + 1;
        String sequencePart = String.format("%03d", sequence);

        // 组装username
        String username = "user_" + datePart + "_" + sequencePart;

        logger.info("生成username: {}", username);
        return username;
    }

    /**
     * 创建新用户
     */
    private User createNewUser(String openid) {
        User user = new User();
        user.setUserId(UUID.randomUUID().toString());
        user.setUsername(generateUsername());
        user.setWechatOpenid(openid);
        user.setStatus("active");
        user.setCreatedAt(LocalDateTime.now());
        user.setLastLoginAt(LocalDateTime.now());
        user.setIsDeleted(false);

        int rows = userMapper.insert(user);
        if (rows == 0) {
            throw new RuntimeException("创建用户失败");
        }

        return user;
    }

    /**
     * 将User实体转换为UserDTO
     */
    private UserDTO convertToDTO(User user) {
        UserDTO dto = new UserDTO();
        BeanUtils.copyProperties(user, dto);
        return dto;
    }
}
